<template>
  <el-row>
    <el-col :span="24">
      <el-table :data="tigerList" stripe border style="width: 100%">
        <el-table-column prop="tigerId" label="编号" width="180"/>
        <el-table-column prop="tigerName" label="名字" width="180"/>
        <el-table-column prop="tigerAge" label="年龄"/>
        <el-table-column prop="tigerSalary" label="工资"/>
        <el-table-column label="操作" #default="scope">
          <el-button type="primary" size="large" :icon="Edit" @click="editClickHandler(scope.row)">编辑</el-button>
          <el-button type="danger" size="large" :icon="Delete" @click="deleteClickHandler(scope.row)">删除</el-button>
        </el-table-column>
      </el-table>
    </el-col>
  </el-row>
  <el-row>
    <el-col :span="24">
      <el-button type="primary" @click="reloadDataClickHandler" size="large" :icon="Refresh">重新加载数据</el-button>
    </el-col>
  </el-row>
</template>

<script setup>
// -----------------------------导入区-----------------------------
import axiosInstance from '../config/axios.js';
import {onMounted, reactive} from "vue";
import {Edit, Delete, Refresh} from "@element-plus/icons-vue"
import {ElMessage, ElMessageBox} from 'element-plus'
import {useRouter} from "vue-router";

// -----------------------------数据区-----------------------------
const tigerList = reactive([]);
let router = useRouter();

// -----------------------------功能区-----------------------------
onMounted(async () => {
  await reloadData();
});

const reloadDataClickHandler = async () => {
  await reloadData();
}

// 声明一个专门的方法：从后端加载数据，并渲染到表格中
const reloadData = async () => {
  // 给后端 Servlet 发送请求，获取响应体数据
  let {data} = await axiosInstance.get("/tiger/list");

  // data 是整个响应体，对应后端 Result 的数据结构
  // data.data 是访问 Result 结构中的 data 属性，也就是真正的查询结果数据
  // console.log(data.data)

  tigerList.splice(0, tigerList.length);

  tigerList.push(...data.data);

  ElMessage.success("Oh yeah!列表加载成功！");
}

// 给删除按钮绑定单击响应函数
const deleteClickHandler = (row) => {
  let message = `您真的要删除【${row.tigerName}】这条记录吗？`;
  let title = '系统提示';
  let confirmConfig = {confirmButtonText: '确定删除', cancelButtonText: '我点错了，不删除', type: 'warning'};

  ElMessageBox.confirm(message, title, confirmConfig)
              .then(async () => {await axiosInstance.delete(`/tiger/${row.tigerId}`)})
              .then(() => {ElMessage.success("Oh yeah!删除成功！")})
              .then(async () => {await reloadData();});

              // 严格全面来讲，catch()传入的回调函数是在前面操作抛异常后执行
              // 而我们已经在全局层面，统一处理了 HTTP 错误和逻辑错误，所以这里这一行代码就舍弃了
              // .catch(() => {ElMessage({type: 'info', message: '好的，不删',})})
}

// 给编辑按钮绑定单击响应函数
const editClickHandler = (row) => {
  router.push(`/edit?tigerId=${row.tigerId}`);
}
</script>

<style scoped>

</style>